package org.glavo.bot

import com.aliyuncs.DefaultAcsClient
import com.aliyuncs.alidns.model.v20150109.DescribeSubDomainRecordsRequest
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest
import com.aliyuncs.profile.DefaultProfile
import org.glavo.bot.data.Config
import kotlin.concurrent.thread

fun ddns() {
    thread(isDaemon = true, name = "DDNS Thread") {
        val profile = DefaultProfile.getProfile("cn-hangzhou", Config.AccessKeyId, Config.AccessSecret)
        val client = DefaultAcsClient(profile)
        val logger = bot.logger

        while (true) {
            val ip = try {
                serverIp()
            } catch (e: Throwable) {
                logger.warning("获取服务器 IP 失败", e)
                Thread.sleep(15 * 1000L)
                continue
            }

            val request1 = DescribeSubDomainRecordsRequest().also {
                it.subDomain = Config.ServerDomain
                it.pageSize = 100
                it.pageNumber = 1
            }

            val records = try {
                client.getAcsResponse(request1).domainRecords
            } catch (e: Throwable) {
                logger.warning("获取解析记录时出现异常", e)
                Thread.sleep(5 * 1000L)
                continue
            }

            val rd = records?.firstOrNull { it.type == "A" }

            if (rd == null) {
                logger.error("当前域名没有 A 记录")
                break
            }

            if (rd.value == ip) {
                logger.info("当前记录不需要更新")
                Thread.sleep(150 * 1000L)
            } else {
                val request2 = UpdateDomainRecordRequest().also {
                    it.recordId = rd.recordId
                    it.rr = rd.rr
                    it.type = rd.type
                    it.ttl = rd.ttl
                    it.value = ip
                }

                try {
                    client.getAcsResponse(request2)
                    logger.info("更新解析记录成功")
                    logger.info("当前公网 IP 为: $ip")
                } catch (e: Throwable) {
                    logger.warning("更新解析记录时异常", e)
                    Thread.sleep(5 * 1000L)
                    continue
                }
                Thread.sleep(180 * 1000L)
            }

        }
    }
}